package com.roger.myHome.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.roger.myHome.entity.qto.RefreshToken;
import com.roger.myHome.service.CacheService;
import com.roger.myHome.service.TokenService;
import com.roger.myHome.util.Constants;
import com.roger.myHome.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class TokenServiceImpl implements TokenService {
    @Resource
    private CacheService cacheService;

    @Override
    public String refresh(RefreshToken refreshToken) {

        Claims claims = JwtUtil.checkToken(refreshToken.getRefreshToken());
        String id = (String) claims.get(Constants.USER_ID);

        Map<String, String> hashMap = new HashMap<String, String>();

        String username = cacheService.findById(Long.valueOf(id)).getUsername();

        hashMap.put("result", "success");
        hashMap.put("token", JwtUtil.getJwtToken(id, username, 1000 * 60 * 60));
        hashMap.put("expireTime", "180000");
        hashMap.put("refreshToken", JwtUtil.getJwtToken(id,username, 1000 * 60 * 60 * 24));

        return JSONArray.toJSONString(hashMap);
    }
}
